package com.ruoyi.web.controller.admin;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.tb.TBConstants;
import com.ruoyi.common.utils.wx.HttpClientSslUtils;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 淘宝开放平台 接口
 */
@RestController()
@RequestMapping("/system/TBapi")
@Api(value = "淘宝API调用", tags = { "淘宝API调用" })
public class TBController {

    // 拿取 accesstoken
    @GetMapping("/getAccesstoken")
    public AjaxResult getAccesstoken() {
        try {
            String get = "https://oauth.taobao.com/authorize?response_type=code&" +
                    "client_id=&" +
                    "redirect_uri=http://www.taobao.com&state=1212&view=web";
            String jsonHttp = HttpClientSslUtils.doGet(get);
            JSONObject jsonObject = JSONObject.parseObject(jsonHttp);
            String error = jsonObject.get("error_response").toString();
            if (StringUtils.isNotEmpty(error)) {
                throw new GlobalException("出现异常");
            }
            return AjaxResult.success(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("调用失败，请联系管理员！");
        }
    }
    @GetMapping("doTrades")
    public AjaxResult doTrades() {
        String method = "taobao.trade.fullinfo.get";
        try {
            String get = "https://gw.api.taobao.com/router/rest?" +
                    "method=" + method+ "&" +
                    "app_key=" + TBConstants.TB_APPKEY + "&" +
                    "session="+ TBConstants.TB_SEESIONKEY +"&" +
                    "timestamp="+ DateUtils.getTime() + "&" +
                    "sign_method=md5&" +
                    "v=2.0&" +
                    "sign=5346F31095B7E519DC789A8289F6A66B&" +
                    "format=json&" +
                    "simplify=false";
            String jsonHttp = HttpClientSslUtils.doGet(get);
            JSONObject jsonObject = JSONObject.parseObject(jsonHttp);
            String error = jsonObject.get("error_response").toString();
            if (StringUtils.isNotEmpty(error)) {
                throw new GlobalException("出现异常");
            }
            return AjaxResult.success(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("调用失败，请联系管理员！");
        }
    }
}
